import 'dart:ui';

import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:mall/components/image_network.dart';
import 'package:mall/core/models/business_level.dart';
import 'package:mall/core/models/business_type.dart';
import 'package:mall/core/services/new_api.dart';
import 'package:mall/screens/manage/business_condition_page.dart';
import 'package:mall/screens/mine/webview_page.dart';
import 'package:provider/provider.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';

/// 选择业务级别
class BusinessLevelScreen extends StatefulWidget {
  const BusinessLevelScreen({
    Key key,
    @required this.args,
  }) : super(key: key);
  static const routeName = '/BusinessLevelScreen';
  final BusinessType args;

  @override
  _BusinessLevelScreenState createState() => _BusinessLevelScreenState();
}

class _BusinessLevelScreenState extends State<BusinessLevelScreen> {
  String _error;
  List<BusinessLevel> _list;

  @override
  void initState() {
    super.initState();
    _fetchBusinessLevel();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('选择业务级别'),
      ),
      body: _error == null && _list == null
          ? Center(
              child: CircularProgressIndicator(),
            )
          : _list == null
              ? Center(
                  child: Text('$_error'),
                )
              : _buildBody(),
    );
  }

  Widget _buildBody() {
    return SingleChildScrollView(
      padding: EdgeInsets.all(10.w),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          _buildHeader(),
          SizedBox(height: 10.w),
          Text('请选择业务级别', style: TextStyle(fontSize: 14.sp)),
          SizedBox(height: 10.w),
          Wrap(
            runSpacing: 5.w,
            children: List.generate(_list.length, (index) => _buildItem(_list[index])),
          ),
        ],
      ),
    );
  }

  Widget _buildHeader() {
    final type = widget.args;
    return Container(
      padding: EdgeInsets.all(8.w),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(4.w),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            children: [
              ImageNetwork(url: '${type.typeImageUrl}', width: 30.w, height: 30.w),
              SizedBox(width: 11.w),
              Text('${type.businessName}', style: TextStyle(fontSize: 16.sp)),
              Spacer(),
              Column(
                children: [
                  Text('${type.maxLevelName}'),
                  Text('最高级别', style: TextStyle(fontSize: 10.sp)),
                ],
              ),
            ],
          ),
          Divider(height: 34.w),
          Row(
            children: [
              Text('您当前的级别：', style: TextStyle(fontSize: 14.sp)),
              Spacer(),
              Text(
                '${type.curBusinessLevelName == null || type.curBusinessLevelName.isEmpty ? '无' : type.curBusinessLevelName}',
                style: TextStyle(fontSize: 14.sp),
              ),
            ],
          ),
          SizedBox(height: 9.w),
        ],
      ),
    );
  }

  Widget _buildItem(BusinessLevel level) {
    return Container(
      padding: EdgeInsets.fromLTRB(8.w, 8.w, 8.w, 0),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(4.w),
      ),
      width: (375 - 10 * 2).w,
      child: Column(
        children: [
          Row(
            children: [
              Text('${level.businessLevelName}', style: TextStyle(fontSize: 14.sp)),
              Spacer(),
              Text('${level.businessTypeName}', style: TextStyle(fontSize: 12.sp)),
            ],
          ),
          Row(
            children: [
              _buildRatingStar(level),
              Spacer(),
              if (!level.enabled) ...[
                FlatButton(
                  minWidth: 0,
                  padding: EdgeInsets.zero,
                  onPressed: () => _onPressedAgreement(level),
                  child: Text('业务协议'),
                ),
                SizedBox(
                  width: 16.w,
                ),
              ],
              FlatButton(
                minWidth: 0,
                padding: EdgeInsets.zero,
                onPressed: level.enabled ? () => _onPressedItem(level) : null,
                child: Text('继续申请'),
              ),
            ],
          ),
        ],
      ),
    );
  }

  Widget _buildRatingStar(BusinessLevel level) {
    var stars = 1;
    switch (level.businessLevel) {
      case 'LEVEL_1':
        stars = 1;
        break;
      case 'LEVEL_2':
        stars = 2;
        break;
      case 'LEVEL_3':
        stars = 3;
        break;
      case 'LEVEL_4':
        stars = 4;
        break;
      case 'LEVEL_5':
        stars = 5;
        break;
      default:
    }
    return Row(
      children: List.generate(
        stars,
        (index) => Icon(Icons.star, size: 16.w, color: Theme.of(context).primaryColor),
      ),
    );
  }

  void _onPressedAgreement(BusinessLevel level) async {
    // 显示协议
    final url = level.businessProtocolUrl;
    if (url != null && url.isNotEmpty) {
      await Navigator.of(context).pushNamed(
        WebViewPage.routeName,
        arguments: WebViewPageArgs(
          '业务申请协议',
          '请仔细阅读以下条款：',
          '$url',
          query: false,
        ),
      );
    }
  }

  void _onPressedItem(BusinessLevel level) async {
    // 显示协议
    final url = level.businessProtocolUrl;
    if (url != null && url.isNotEmpty) {
      final result = await Navigator.of(context).pushNamed(
        WebViewPage.routeName,
        arguments: WebViewPageArgs(
          '业务申请协议',
          '请仔细阅读以下条款：',
          '$url',
          query: true,
        ),
      );
      if (result == null || result == false) {
        return;
      }
    }

    // 继续申请
    Navigator.of(context).pushNamed(BusinessConditionPage.routeName, arguments: level);
  }

  void _fetchBusinessLevel() async {
    final api = context.read<NewApi>();
    try {
      final list = await api.businessLevel(widget.args.businessType);
      if (!mounted) {
        return;
      }
      setState(() {
        _list = list;
      });
    } on DioError catch (e) {
      if (!mounted) {
        return;
      }
      setState(() {
        _error = e.message;
      });
    }
  }
}
